
#include <QDateTime>
#include <QFileDialog>
#include <QMessageBox>
#include <QXmlStreamWriter>

#include "NouveauClient.h"
#include "TrueLove.h"


NouveauClient::NouveauClient(QWidget* parent)
: QMainWindow(parent), Ui_NouveauClient()
{
	setupUi(this);
	this->listWidget_hobbies->setDragEnabled(false);
}

void NouveauClient::choisirPhotoClient()
{
	QString stylesheet("background-position: center; background-image: url('");
	this->photoPath = QFileDialog::getOpenFileName(this, tr("Choisir une photo de vous..."), 
			"./", tr("Image Files (*.png *.jpg *.bmp)"));

	stylesheet.append(this->photoPath);
	stylesheet.append("');");
	this->graphicsView_photoClient->setStyleSheet(stylesheet);
}

void NouveauClient::majHobbies()
{
	int count = this->listWidget_hobbies->selectedItems().count();
	if(count > 3)
	{
	}
}

void NouveauClient::closeEvent(QCloseEvent *event)
{
	retourAccueil();
}

void NouveauClient::majPhotoPersonne()
{
	QString s = this->comboBox_sexePersonne->currentText();
	QString stylesheet_pict("background-image: url('./icons/");
	QString stylesheet_wdgt("background-image: url('./icons/");

	if(s.compare("Homme") == 0)
	{
		stylesheet_pict.append("men.jpg");
		stylesheet_wdgt.append("gradient-men.png");
	}
	else if(s.compare("Femme") == 0)
	{
		stylesheet_pict.append("women.jpg");
		stylesheet_wdgt.append("gradient-women.png");
	}
	else
	{
		stylesheet_pict.append("nobody.png");
		stylesheet_wdgt.append("gradient-client.png");
	}

	stylesheet_pict.append("');");
	stylesheet_wdgt.append("');");
	this->graphicsView_photoPersonne->setStyleSheet(stylesheet_pict);
	this->widget_2->setStyleSheet(stylesheet_wdgt);
}

void NouveauClient::retourAccueil()
{
	deleteLater();
	parentWidget()->show();
}

void NouveauClient::enregistrerClient()
{
	QString errors = "<p><b>Il y a des erreurs dans le formulaire:</b></p><ul>";
	QRegExp regexMail("^([a-zA-Z]|.){1,}@[a-zA-Z]{1,}.[a-zA-Z]{2,3}$");
	bool isError = false;

	int apparence = lcdNumber_apparencePersonne->intValue();
	int charme = lcdNumber_charmePersonne->intValue();
	int humour = lcdNumber_humourPersonne->intValue();
	int conversation = lcdNumber_conversationPersonne->intValue();
	int intelligence = lcdNumber_intelligencePersonne->intValue();
	int gentillesse = lcdNumber_gentillessePersonne->intValue();

	TrueLoveClient c;
	c.SetAdress(textEdit_addresseClient->toPlainText());
	c.SetAge(spinBox_ageClient->value());
	c.SetDiffAge(spinBox_differenceAgePersonne->value());
	c.SetSexeRecherche(comboBox_sexePersonne->currentText());

	// Vérification du prénom:
	if(lineEdit_prenomClient->text() == NULL || lineEdit_prenomClient->text().length() < 2)	
	{
		errors.append(
				"<li>Le pr&eacute;nom doit &ecirc;tre compos&eacute; d'au moins deux lettres.</li>");
		isError = true;
	}
	else
	{
		c.SetPrenom(lineEdit_prenomClient->text().trimmed());
	}

	// Vérification du nom:
	if(lineEdit_clientNom->text() == NULL || lineEdit_clientNom->text().length() < 2)
	{
		errors.append("<li>Le nom doit &ecirc;tre compos&eacute; d'au moins deux lettres.</li>");
		isError = true;
	}
	else	
	{
		c.SetNom(lineEdit_clientNom->text().trimmed());
	}

	// Vérification de l'adresse:
	if(!lineEdit_eMailClient->text().contains(regexMail))	
	{
		errors.append("<li>L'adresse e-mail n'est pas valide.</li>");
		isError = true;
	}
	else
	{
		c.SetEmail(lineEdit_eMailClient->text().trimmed());
	}

	// Vérification de l'objectif de la rencontre:
	if(!checkBox_grandAmour->isChecked() && !checkBox_amourPassionne->isChecked())
	{
		errors.append("<li>L'objectif de la rencontre n'est pas sp&eacute;cifi&eacute;.</li>");
		isError = true;
	}
	else
	{
		QList<QString> objs;

		if(checkBox_grandAmour->isChecked()) 		objs.append("grandamour");
		if(checkBox_amourPassionne->isChecked()) 	objs.append("amourpassionne");

		c.SetObjectifs(objs);
	}

	// Vérification de la présence d'une photo de profil:
	if(this->photoPath == NULL || this->photoPath.length() == 0)
	{
		errors.append("<li>La photo de profil est manquante.</li>");
		isError = true;
	}
	else
	{
		c.SetUrlPhoto(this->photoPath);
	}

	// Vérification du sexe:
	if(radioButtonHomme->isChecked())
		c.SetSexe("Homme");
	else
		c.SetSexe("Femme");

	// Vérification du nombre de hobbies:
	if(this->listWidget_hobbies->selectedItems().count() > MAX_HOBBIES)
	{
		errors.append(QString("<li>Seulement %1 hobbies peuvent &ecirc;tre choisis.</li>")
				.arg(MAX_HOBBIES));
		isError = true;
	}
	else
	{
		QList<QString> hobbies;

		for(int i=0; i < this->listWidget_hobbies->selectedItems().count(); i++)
			hobbies.append(listWidget_hobbies->selectedItems().at(i)->text());

		c.SetHobbies(hobbies);
	}

	// Vérification du nombre de points attribués à la personne recherchée par rapport aux
	// nombre de points alloués:
	if(apparence + charme + humour + intelligence + conversation + gentillesse > MAX_POINTS_CRITERES)
	{
		errors.append(QString(
			"<li>Seulement %1 points de crit&egrave;res peuvent &ecirc;tre allou&eacute;s.</li>").arg(MAX_POINTS_CRITERES));
	}
	else
	{
		c.SetApparence(apparence);
		c.SetCharme(charme);
		c.SetHumour(humour);
		c.SetConversation(conversation);
		c.SetIntelligence(intelligence);
		c.SetGentillesse(gentillesse);
	}

	if(isError)
	{
		errors.append("</ul>");
		QMessageBox::critical(this, "TrueLove | ERREUR", errors);
	}
	else
	{
		QFile photo(this->photoPath);
		QStringList list = this->photoPath.split(".");
		QString ext = list.at(list.size()-1);
		QString newPath = QString("pics/%1_%2.%3").arg(c.GetNom()).arg(c.GetPrenom()).arg(ext);
		bool error_success = photo.copy(newPath);
		
		if(!error_success) 
			printf("ERREUR: copie du fichier image.\n");
		else
			c.SetUrlPhoto(newPath);
		
		c.SetId(QDateTime::currentDateTime().toTime_t());
		enregistrerClientXML(c);
		QMessageBox::information(this, "TrueLove | Fin de la saisie...", 
			"<p><b>Client enregistr&eacute; avec succ&egrave;s!</b></p>Cliquez sur Ok pour revenir &agrave; l'accueil.");
		this->deleteLater();
		parentWidget()->show();
	}	
}

void NouveauClient::enregistrerClientXML(TrueLoveClient c)
{
	QFile* file = new QFile("xml/clients.xml");
	QList<TrueLoveClient> existingClients = TrueLoveClient::GetClients();

	if(file->open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QXmlStreamWriter* writer = new QXmlStreamWriter(file);
		writer->setAutoFormatting(true);

		writer->writeStartDocument(); // XML header
		writer->writeStartElement("clients");

		for(int i=0; i<existingClients.size(); i++)
			AddClientXmlProperties(writer, existingClients.at(i));

		AddClientXmlProperties(writer, c);

		writer->writeEndElement();	// </clients>
		writer->writeEndDocument();
		file->close();
	}
}

void NouveauClient::enregistrerClientsXML(QList<TrueLoveClient> clients)
{
	QFile* file = new QFile("xml/clients.xml");

	if(file->open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QXmlStreamWriter* writer = new QXmlStreamWriter(file);
		writer->setAutoFormatting(true);

		writer->writeStartDocument(); // XML header
		writer->writeStartElement("clients");

		for(int i=0; i<clients.size(); i++)
			AddClientXmlProperties(writer, clients.at(i));

		writer->writeEndElement();	// </clients>
		writer->writeEndDocument();
		file->close();
	}
}

void NouveauClient::AddClientXmlProperties(QXmlStreamWriter* writer, TrueLoveClient c)
{
	writer->writeStartElement("client");
	
	writer->writeTextElement("id", QString("%1").arg(c.GetId()));
	writer->writeTextElement("nom", c.GetNom());
	writer->writeTextElement("prenom", c.GetPrenom());
	writer->writeTextElement("age", QString("%1").arg(c.GetAge()));
	writer->writeTextElement("adress", c.GetAdress());
	writer->writeTextElement("email", c.GetEmail());
	for(int i=0; i<c.GetHobbies().count(); i++)
		writer->writeTextElement("hobby", c.GetHobbies().at(i));

	for(int i=0; i<c.GetObjectifs().count(); i++)
		writer->writeTextElement("objectif", c.GetObjectifs().at(i));
	
	writer->writeTextElement("sexe", c.GetSexe());
	writer->writeTextElement("sexeRecherche", c.GetSexeRecherche());
	writer->writeTextElement("diffAge", QString("%1").arg(c.GetDiffAge()));
	writer->writeTextElement("apparence", QString("%1").arg(c.GetApparence()));
	writer->writeTextElement("charme", QString("%1").arg(c.GetCharme()));
	writer->writeTextElement("humour", QString("%1").arg(c.GetHumour()));
	writer->writeTextElement("conversation", QString("%1").arg(c.GetConversation()));
	writer->writeTextElement("intelligence", QString("%1").arg(c.GetIntelligence()));
	writer->writeTextElement("gentillesse", QString("%1").arg(c.GetGentillesse()));
	writer->writeTextElement("urlPhoto", c.GetUrlPhoto());
		
	writer->writeEndElement();	// </client>	
}

NouveauClient::~NouveauClient(){}

